<template>
    <Layout :style="{padding: '0 6px 6px'}">
        <grid-table 
            :tablecolumns="tablecolumns" 
            :tabledata="tabledata" 
            :creatrouter="creatrouter" 
            :editrouter="editrouter"
            :title="title"
            :fullscreen="fullscreen"
            :showmodal="showmodal"
            :loadingTable="loadingtable"
            :keyword="keyword"
            :routeroot="routeroot"
            :modalname="modalname"
            :vuexnamespace="vuexnamespace"
            :query="QueryResult"
            :advancemethod="AdvanceShow"
            :dataoption="true"
            :advancequery = "true"
            :handledata="HandleData"
            :deletesingle="DeleteCashFlowSingle"
            :deletelist="DeleteCashFlowList"
            :handleSummary="HandleSummary"
            :isSummary="true"
            :pageIndex="pageIndex"
            :pageSize="pageSize"/>
        
        <Footer :style="{ background: 'white',padding: '15px 10px 10px',borderRadius: '10px'}">
            <Page 
                :style="{ textAlign:'right',marginTop: '0px',paddingRight: '0px',background: 'white'}"
                show-sizer 
                show-elevator 
                show-total 
                :total="total"
                :page-size="pageSize"
                :page-size-opts="pageSizeOpts"
                @on-change="ChangePage"
                @on-page-size-change="ChangePageSize"/>
        </Footer>
        <Modal 
            v-model="AdvanceModal"
            :draggable="true"
            @on-cancel="CancelAdvanceQuery"
            :footer-hide="true"
            title="高级查询">
            <Content>
                <Form ref="advance" :model="advance" :rules="ruleValidate" :label-width="130" :style="{ marginTop: '15px'}">
                    <Row>
                        <Col span="20">
                            <FormItem label="银行或项目名称">
                                <Input v-model="advance.BankOrProject" placeholder="请输入查询信息！" style="width: 300px" />
                            </FormItem>
                        </Col>
                        <Col span="20">
                            <FormItem label="金额范围">
                                <p style="width: 300px">
                                <Input v-model="advance.MinMoney" placeholder="查询金额下限" style="width: 132px" />
                                ——
                                <Input v-model="advance.MaxMoney" placeholder="查询金额上限" style="width: 132px" />
                                </p>
                            </FormItem>
                        </Col>
                        <Col span="20" style="z-index:1500;">
                            <FormItem label="款项类型">
                                <Select v-model.trim="advance.FundsType" filterable clearable style="width: 300px">
                                    <Option v-for="item in FundsTypes" :value=item.value :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="10" style="z-index:1000;">
                            <FormItem label="金额方向">
                                <Select v-model.trim="advance.BookMark"  filterable clearable style="width: 98px;" >
                                    <Option value=0 >收入</Option>
                                    <Option value=1 >支出</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="10" style="z-index:500;">
                            <FormItem label="款项状态">
                                <Select v-model.trim="advance.FundsStatus" filterable clearable style="width: 98px" >
                                    <Option value=0 >待确认</Option>
                                    <Option value=1 >已确认</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="20">
                            <FormItem label="时间范围">
                                <DatePicker v-model="advance.DateRange" format="yyyy年MM月dd日" type="daterange" clearable placement="bottom-end" placeholder="请选择时间区间" style="width: 300px"></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="20" >
                            <FormItem label="操作人" >
                                <Select v-model.trim="advance.Operator" filterable clearable style="width: 300px">
                                    <Option v-for="item in Operators" :value=item.value :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="20" offset="2" style="text-align:center;margin-top:10px;margin-bottom:25px;">
                            <Button type="primary" @click="AdvanceQuery">开始查询</Button>
                            <Button @click="ClearAdvance" style="margin-left: 50px">清除条件</Button>
                        </Col>
                    </Row>
                </Form>
            </Content>
        </Modal>
        <Modal
            v-model="HandleDataModal"
            :footer-hide="true"
            :title="HandleDataTitle">
            <Content>
                <Form ref="HandleDataForm" :model="HandleDataForm" :rules="ruleValidate" :label-width="100" :style="{ marginTop: '15px'}">
                    <Row v-if="ImportOrExport">
                        <Col span="20">
                            <FormItem label="导入方式" prop="ImportWay">
                                <Select v-model.number="HandleDataForm.ImportWay">
                                    <Option v-for="item in ImportWay" :value="item.value" :key="item.value">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="20" v-if="HandleDataForm.ImportWay == 0">
                            <FormItem label="付款银行" prop="BankName">
                                <AutoComplete
                                    v-model="HandleDataForm.BankName"
                                    icon="ios-search"
                                    placeholder="请输入银行名称！"
                                    clearable
                                    @on-search="SearchBank"
                                    @on-select="SelectBank"
                                    @on-clear="ClearBank"
                                    style="width:100%">
                                    <div class="auto-complete-item" v-for="item in Banks" :key="item.OrderNum">
                                        <div class="auto-complete-group">
                                            <span style="margin-left: 10px;">{{ item.Company }}</span>
                                            <!-- <a href="https://www.baidu.com/search?q=iView" target="_blank">更多</a> -->
                                        </div>
                                        <Option v-for="option in item.Children" :value="option.Id" :key="option.Id">
                                            <span class="auto-complete-title">{{ option.Name }}</span>
                                            <span class="auto-complete-count">{{ option.Account.substr(option.Account.length-4,4) }} 账户尾号</span>
                                        </Option>
                                    </div>
                                    <!-- <a href="https://www.baidu.com/" target="_blank" class="auto-complete-more">查看所有结果</a> -->
                                </AutoComplete>
                            </FormItem>
                        </Col>
                        <Col span="20">
                            <FormItem label="上传文件" prop="UploadFile">
                                <Upload
                                    :action="UploadURL"
                                    :headers="UploadHeader"
                                    type="drag"
                                    :max-size="1048576"
                                    :on-success="UploadSuccess"
                                    :on-error="UploadError"
                                    :on-remove="RemoveUpload"
                                    accept=".xls,.xlsx">
                                    <Button icon="ios-cloud-upload" style="width:100%;height:34px">选择上传文件</Button>
                                </Upload>
                            </FormItem>
                        </Col>
                        <Col span="20">
                            <FormItem label="模板文件">
                                <a :href="DownloadFundsURL" v-if="this.HandleDataForm.ImportWay == 0">Excel导入模板</a>
                                <a :href="DownloadBatchURL" v-else>Excel导入模板</a>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row v-if="!ImportOrExport">
                        <Col span="20" >
                            <FormItem label="时间区间">
                                <DatePicker type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="请选择导出时间区间" style="width: 100%"></DatePicker>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="20" offset="2" style="text-align:center;margin-top:10px;margin-bottom:25px;">
                            <Button v-if="ImportOrExport" type="primary" @click="Import('HandleDataForm')">导入</Button>
                            <Button v-else type="primary" @click="Export('HandleDataForm')">导出</Button>
                            <Button @click="Cancel('HandleDataForm')" style="margin-left: 50px">取消</Button>
                        </Col>
                    </Row>
                </Form>
            </Content>
            <!-- <Content v-else>
                <Form ref="HandleDataForm" :model="HandleDataForm" :rules="ruleValidate" :label-width="100" :style="{ marginTop: '15px'}">
                    <Row>

                    </Row>
                    <Row>
                        <Col span="20" offset="2" style="text-align:center;margin-top:10px;margin-bottom:25px;">
                            <Button type="primary" @click="Import('HandleDataForm')">导出</Button>
                            <Button @click="Cancel('HandleDataForm')" style="margin-left: 50px">取消</Button>
                        </Col>
                    </Row>
                </Form>
            </Content> -->
        </Modal>
        <Modal 
            fullscreen 
            v-model="FailTable" 
            title="导入失败列表"
            ok-text="导出"
            cancel-text="关闭"
            @on-ok="ExportFailList">
            <Table stripe :columns="FailHeadTitle" :data="FailImportList" ref="FailTableDetail"></Table>
        </Modal>
    </Layout>
</template>
<script>
import { 
    DeleteSingle,
    DeleteList,
    QueryBankInfo,
    QueryBankById,
    BatchImport,
    DeleteUploadFile,
    LoadFundsType,
    LoadOperators
} from '@/axios/api/CashFlowAPI'
import { getToken,getUserInfo } from "@/store/localStorage/cookies";
import GridTable from '@/components/GridTable/index'
import { mapState } from "vuex";

export default {
    name: 'CashFlow',
    components: { GridTable },
    data() {
        const UploadFileCheck = (rule,value,callback) => {
            if (this.HandleDataForm.Importfile === '') {
                callback(new Error('请上传文件！'));
            }
            else{
                callback();
            }
        };
        return {
            vuexnamespace: "cashflow",
            modalname: "CashFlow",
            routeroot: 'funds',
            keyword: '',
            advance: {
                BankOrProject:'',
                FundsStatus: '',
                BookMark: '',
                MaxMoney: "",
                MinMoney: "",
                FundsType: '',
                Operator: '00000000-0000-0000-0000-000000000000',
                DateRange: ""
            },
            FundsTypes:[],
            Operators:[],
            Banks: [],
            UploadHeader: {
                Authorization: getToken()
            },
            UploadURL: process.env.VUE_APP_BASE_API + "/CashFlow/UploadImportFile",
            DownloadFundsURL: process.env.VUE_APP_BASE_API + "/CashFlow/DownloadExportFile?importType=0",
            DownloadBatchURL: process.env.VUE_APP_BASE_API + "/CashFlow/DownloadExportFile?importType=1",
            HandleDataModal: false,
            AdvanceModal: false,
            ImportOrExport: true,
            HandleDataTitle: '',
            FailImportList: [],
            FailTable: false,
            FailHeadTitle: [
                {
                    title: '银行账户',
                    key: 'BankAccount'
                },
                {
                    title: '项目名称',
                    key: 'ProjectName'
                },
                {
                    title: '供应商',
                    key: 'SupplierFactory'
                },
                {
                    title: '金额方向',
                    key: 'MoneyForward'
                },
                {
                    title: '款项类别',
                    key: 'FundsType'
                },
                {
                    title: '金额',
                    key: 'Amount'
                },
                {
                    title: '摘要',
                    key: 'Summary'
                },
                {
                    title: '入账日期',
                    key: 'AllocationTime'
                },
                {
                    title: '失败原因',
                    key: 'FailReason'
                }
            ],
            ImportWay: [
                { 
                    value: 0,
                    label: "资金付款表"
                },
                { 
                    value: 1,
                    label: "批量导入"
                }
            ],
            HandleDataForm: {
                BankGuid: '00000000-0000-0000-0000-000000000000',
                BankName: '',
                Payer: '00000000-0000-0000-0000-000000000000',
                Importfile: '',
                ImportWay: 0,
            },
            ruleValidate: {
                ImportWay: [{ type: 'number', message: '只能输入数字', trigger: 'blur' }],
                BankName: [{ required: true, message: '必须输入银行！', trigger: 'blur' }],
                UploadFile: [{ validator: UploadFileCheck, message: '请上传导入文件！', trigger: 'blur' }]
            }
        }
    },
    watch: {
        'HandleDataForm.BankGuid'(value){
            QueryBankById(value).then(res => {
                if(res){
                    this.HandleDataForm.BankGuid = res.Id;
                    this.HandleDataForm.BankName = res.Name;
                }
            })
        },
        'advance.BankOrProject'(value){
            this.keyword = value;
        }
    },
    mounted: function(){
        //console.log(process.env)
        var currentUserInfo = JSON.parse(getUserInfo());
        this.HandleDataForm.Payer = currentUserInfo.Id;
        this.ImportOrExport = true;

        //获取款项类型
        LoadFundsType().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Code.toString(),
                    label: item.Name
                };
            });
            this.FundsTypes = list;
        })

        //获取款项类型
        LoadOperators().then(res => {
            const list = res.map(item => {
                return {
                    value: item.Id.toString(),
                    label: item.RealName
                };
            });
            this.Operators = list;
        })
    },
    computed: {
        ...mapState('cashflow',[
            'tablecolumns',
            'tabledata',
            'creatrouter',
            'editrouter',
            'title',
            'loadingtable',
            'fullscreen',
            'showmodal',
            'total',
            'pageIndex',
            'pageSize',
            'pageSizeOpts'
        ])
    },
    created: function(){
        this.$store.dispatch('cashflow/InitCashFlow',{
            CreatRouter: 'CashFlow/CashFlow-sheet',
            EditRouter: 'CashFlow/Cashflow-Sheet',
            PageIndex: this.pageIndex,
            PageSize: this.pageSize,
            Keyword: this.keyword,
            Advance: this.advance
        })
    },
    methods: {
        ChangePage(pageIndex){
            console.log(this.advance)

            this.$store.dispatch('cashflow/ChangePageIndex',{
                PageIndex: pageIndex,
                PageSize: this.pageSize,
                Keyword: this.keyword,
                Advance: this.advance
            })
        },
        ChangePageSize(pageSize){

            this.$store.dispatch('cashflow/ChangePageSize',{
                PageIndex: this.pageIndex,
                PageSize: pageSize,
                Keyword: this.keyword,
                Advance: this.advance
            })
        },
        DeleteCashFlowSingle(selectedRow){
            if(selectedRow){
                DeleteSingle(selectedRow).then(res => {
                    if(res > 0){
                        this.$Notice.success({
                            title: '操作成功',
                            desc: '删除成功！ '
                        });

                        this.$store.dispatch('cashflow/UpdateTableAsync',{
                            PageIndex: this.pageIndex,
                            PageSize: this.pageSize,
                            Keyword: this.keyword,
                            Advance: this.advance
                        });
                    }
                    else{
                        this.$Notice.error({
                            title: '操作失败',
                            desc: '删除失败！ '
                        });
                    }
                }).catch(err =>{
                    this.$Notice.error({
                        title: '操作提示',
                        desc: '删除失败：' + err.data + '!'
                    });
                })
            }
        },
        DeleteCashFlowList(selectedRows){
            console.log(selectedRows)
            if(selectedRows){
                DeleteList(selectedRows).then(res => {
                    if(res > 0){
                        this.$Notice.success({
                            title: '操作成功',
                            desc: '批量删除成功！ '
                        });

                        this.$store.dispatch('cashflow/UpdateTableAsync',{
                            PageIndex: this.pageIndex,
                            PageSize: this.pageSize,
                            Keyword: this.keyword,
                            Advance: this.advance
                        });
                    }
                    else{
                        this.$Notice.error({
                            title: '操作失败',
                            desc: '批量删除失败！ '
                        });
                    }
                }).catch(err =>{
                    this.$Notice.error({
                        title: '操作提示',
                        desc: '批量删除失败！' + err.data + '!'
                    });
                })
            }
        },
        HandleSummary({ columns, data }){
            const sums = {};
            columns.forEach((column, index) => {
                const key = column.key;
                if (index === 2) {
                    sums[key] = {
                        key,
                        value: '合计',
                    };
                    return;
                }

                const values = data.map(item => Number(item[key]));
                if (!values.every(value => isNaN(value)) && index == 11) {
                    const v = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[key] = {
                        key,
                        value: v.toFixed(2) 
                    };
                } else {
                    sums[key] = {
                        key,
                        value: ''
                    };
                }
            });

            return sums;
        },
        QueryResult(keyword){
            this.keyword = keyword;
            this.$store.dispatch('cashflow/UpdateTableAsync',{
                PageIndex: this.pageIndex,
                PageSize: this.pageSize,
                Keyword: this.keyword,
                Advance: this.advance
            });
        },
        AdvanceShow(keyword){
            this.keyword = keyword;
            this.AdvanceModal = true;
        },
        AdvanceQuery(){
            this.AdvanceModal = false;
            this.$store.dispatch('cashflow/UpdateTableAsync',{
                PageIndex: this.pageIndex,
                PageSize: this.pageSize,
                Keyword: this.keyword,
                Advance: this.advance
            });
        },
        CancelAdvanceQuery(){
            /* this.advance = {
                BankOrProject:'',
                FundsStatus: '',
                BookMark: '',
                MaxMoney: "",
                MinMoney: "",
                FundsType: '',
                Operator: '00000000-0000-0000-0000-000000000000',
                DateRange: ""
            }; */
            this.$store.dispatch('cashflow/UpdateTableAsync',{
                PageIndex: this.pageIndex,
                PageSize: this.pageSize,
                Keyword: this.keyword,
                Advance: this.advance
            });
        },
        ClearAdvance(){
            this.advance = {
                BankOrProject: "",
                FundsStatus: "",
                BookMark: "",
                MaxMoney: "",
                MinMoney: "",
                FundsType: '',
                Operator: '00000000-0000-0000-0000-000000000000',
                DateRange: ""
            };
        },
        HandleData(name){
            switch(name){
                case "ImportData":
                    this.HandleDataModal = true;
                    this.ImportOrExport = true;
                    this.HandleDataTitle = (this.ImportOrExport ? "导入数据":"导出数据");
                    //console.log(">>>>>>>>>>>>>ImportData",this.ImportOrExport)
                    break;
                case "ExportData":
                    this.HandleDataModal = true
                    this.ImportOrExport = false;
                    this.HandleDataTitle = (this.ImportOrExport ? "导入数据":"导出数据");
                    //console.log(">>>>>>>>>>>>>ExportData",this.ImportOrExport)
                    break;
                default:
                    this.HandleDataModal = true
                    this.ImportOrExport = false;
                    this.HandleDataTitle = (this.ImportOrExport ? "导入数据":"导出数据");
                    //console.log(">>>>>>>>>>>>>Default",this.ImportOrExport)
                    break;
            }
        },
        SearchBank(value){
            QueryBankInfo(value).then(res => {
                this.Banks = res;
            })
        },
        SelectBank(value){
            if(value){
                this.HandleDataForm.BankGuid = value;
            }
        },
        ClearBank(){
            this.HandleDataForm.BankGuid = '00000000-0000-0000-0000-000000000000';
            this.HandleDataForm.BankName = '';
            this.Banks = [];
        },
        UploadSuccess(response){
            
            this.HandleDataForm.Importfile = response.Importfile;
        },
        UploadError(){
            this.HandleDataForm.Importfile = "";
        },
        RemoveUpload(){
            DeleteUploadFile(this.HandleDataForm.Importfile);
        },
        Import(name){

            this.HandleDataModal = false;

            this.$Spin.show();

                        
            /* setTimeout(() => {
                this.$Spin.hide();
                this.$Notice.error({
                    title: '操作提示',
                    desc: '导入操作超时！ '
                });
            }, process.env.VUE_APP_TIMEOUT); */

            console.log(process.env.VUE_APP_TIMEOUT);

            this.$refs[name].validate((valid) => {
                if (valid) {
                    //console.log(this.HandleDataForm);
                    BatchImport(this.HandleDataForm).then(res => {

                        this.FailImportList = res;

                        if(this.FailImportList.length == 0){
                            this.$Notice.success({
                                title: '操作提示',
                                desc: '导入成功！ '
                            });
                        }
                        else{
                            this.$Notice.error({
                                title: '操作提示',
                                desc: '导入失败！ '
                            });

                            this.FailTable = true
                        }

                        this.$store.dispatch('cashflow/UpdateTableAsync',{
                            PageIndex: this.pageIndex,
                            PageSize: this.pageSize
                        });

                        this.HandleDataModal = false;

                        this.HandleDataForm.BankGuid = '00000000-0000-0000-0000-000000000000';
                        this.HandleDataForm.BankName = '';
                        this.HandleDataForm.Importfile = "";
                        this.Banks = [];

                        this.$Spin.hide();
                    })
                    
                } else {
                    this.$Message.error('校验失败!');
                }
            })
        },
        Export(name){
            this.$refs[name].validate((valid) => {
                if (valid) {
                    alert('校验通过！');
                    this.HandleDataModal = false;
                } else {
                    this.$Message.error('校验失败!');
                }
            })
        },
        ExportFailList(){
            //FailTableDetail
            this.$refs.FailTableDetail.exportCsv({
                filename: '导入失败数据'
            });
        },
        Cancel(){
            this.HandleDataForm.BankGuid = '00000000-0000-0000-0000-000000000000';
            this.HandleDataForm.BankName = '';
            this.HandleDataForm.Importfile = "";
            this.Banks = [];
            this.HandleDataModal = false;
        }
    }
}
</script>
<style scoped>
    .auto-complete-item{
        padding: 4px 0;
        width: 450px;
        border-bottom: 1px solid #F6F6F6;
    }
    .auto-complete-group{
        font-size: 12px;
        padding: 4px 6px;
        margin-bottom:10px;
    }
    .auto-complete-group span{
        color: #666;
        font-weight: bold;
    }
    .auto-complete-group a{
        float: right;
    }
    .auto-complete-count{
        float: right;
        color: #999;
    }
    .auto-complete-more{
        display: block;
        margin: 0 auto;
        padding: 4px;
        text-align: center;
        font-size: 12px;
    }
    label.ivu-form-item-label{
        z-index: -10000;
    }
</style>